package com.hantanger.weblog.freemarker;

import java.io.File;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import freemarker.core.Configurable;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateHashModel;

/**
 * @author lys
 *
 */
public class StringMerger {
	
	public StringMerger(){
		setDirectoryForTemplateLoading("WEB-INF/template/");
	}
	
	private Configuration cfg;
	
	public void setDirectoryForTemplateLoading(String directory) {
		try {
			cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File(directory));
			cfg.setDefaultEncoding("utf-8");
			cfg.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
			TemplateHashModel staticModels = BeansWrapper.getDefaultInstance().getStaticModels();
			cfg.setSharedVariable("Utils", staticModels.get("weblog.freemarker.Utils"));
			cfg.setSharedVariable("compresscn", new CompressCN());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void mergeTemplate(Map<String,Object> data, String templateFileName,
			Writer writer) {
		try {
			cfg.setLocale(Locale.ENGLISH);
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			cfg.setSetting(Configurable.NUMBER_FORMAT_KEY, "###0.##");
			Template temp = cfg.getTemplate(templateFileName);
			if (data == null) {
				data = new HashMap<String,Object>();
			}
			temp.process(data, writer);
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String mergeTemplate(Map<String,Object> data, String templateFile){
		StringWriter sw = new StringWriter();
		mergeTemplate(data, templateFile, sw);
		return sw.toString();
	}
}
